package ru.dadle8.service.impl.db;

import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.telegram.telegrambots.meta.api.objects.User;
import ru.dadle8.model.db.DbUser;
import ru.dadle8.model.db.TelegramProfile;
import ru.dadle8.repository.UserRepository;
import ru.dadle8.service.api.db.UserService;

import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;

    @Override
    public Optional<TelegramProfile> getTelegramProfile(Long userId) {
        Optional<DbUser> dbUser = userRepository.findByTelegramProfile_UserId(userId);
        return dbUser.map(DbUser::getTelegramProfile);
    }

    @Override
    public void save(User user, Long chatId) {
        DbUser dbUser = new DbUser();
        TelegramProfile telegramProfile = new TelegramProfile(
                user.getId(),
                user.getUserName(),
                String.join(StringUtils.SPACE, user.getFirstName(), user.getLastName()),
                user.getFirstName(),
                chatId
        );
        dbUser.setRole(List.of(2));
        dbUser.setTelegramProfile(telegramProfile);
        userRepository.save(dbUser);
    }

    @Override
    public boolean exists(Long userId) {
        Optional<DbUser> dbUser = userRepository.findByTelegramProfile_UserId(userId);
        return dbUser.isPresent();
    }
}
